function uploadFile() {
    $("#uploadMessages").hide();
    $("#fileName").attr("value", null);
    $("#uploadResult").val("");
    $("#uploadTemplateForm").ajaxSubmit({
        type: 'POST',
        dataType: 'json',
        beforeSubmit: uploadFileBefore,
        clearForm: true,
        resetForm: true,
        success: function (data) {
            var msgType = data.msgType;
            if ("success" == msgType) {
                getUploadStatus(data.uuid);
                if ($("#uploadResult").val() == "") {
                    var intervalId = setInterval("getUploadStatus('" + data.uuid + "')", 10000);
                    $("#intervalId").val(intervalId);
                }
            }
            if ("failed" == msgType) {
                var errorMsg = data.errorMsg;
                var msg = "Upload Failure!";
                if (undefined != errorMsg && null != errorMsg) {
                    msg += errorMsg;
                }
                showUploadMessages(msg, 'red');
                afterUploadFile();
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            afterUploadFile();
            showUploadMessages("Failure.We are sorry that upload progress has encountered an error, please try again!", 'red');
        }
    });
}
function getUploadStatus(uuid) {
    $.ajax({
        type: "POST",
        url: golbalRootUrl + "catalog/upload/status",
        data: "uuid=" + uuid,
        async: false,
        success: function (result) {
            $("#uploadResult").val(result.jobStatus);
        },
        error: function () {
            $("#uploadResult").val("failed");
        }
    });
    if ($("#uploadResult").val() != "") {
        processUploadStatus();
    }
}

function processUploadStatus() {
    if ($("#uploadResult").val() == "SUCCESS") {
        showUploadMessages("Success,Please wait for 5-10 minutes to get upload result", 'green');
        searchUploadResult();
    } else {
        showUploadMessages("Failure.We are sorry that upload progress has encountered an error, please try again!", 'red');
    }
    afterUploadFile();
    window.clearInterval($("#intervalId").val());
    $("#intervalId").val("0");
}
function afterUploadFile() {
    $('#uploadButton').attr("value", "Upload");
    $('#loadingLogo').css("display", "none");
    $('#uploadButton').removeAttr("disabled");
    $('#uploadButton').parent().removeClass("cancelButtonBox").addClass("orangeButtonBox");
    $('#uploadButton').focus();
}

function uploadFileBefore(formData, jqForm, options) {
    $("#uploadMessages").html('').hide();
    $("#errorMsgInfo").html('');
    var file = $("#file").val();
    if (null == file || "" == file) {
        showUploadMessages('Please select a file to upload.', 'red');
        return false;
    }
    if (null != file && "" != file && (".xls" != file.substring(file.length - 4).toLowerCase() && ".xlsx" != file.substring(file.length - 5).toLowerCase() && ".xlsm" != file.substring(file.length - 5).toLowerCase())) {
        showUploadMessages("File must be uploaded in a xls or xlsx format.", 'red');
        $("#uploadTemplateForm").clearForm();
        $("#uploadTemplateForm").resetForm();
        return false;
    }
    $('#uploadButton').attr("disabled", true);
    $('#uploadButton').parent().removeClass("orangeButtonBox").addClass("cancelButtonBox");
    $('#uploadButton').attr("value", "Uploading...");
    $('#loadingLogo').css("display", "inline-block");
    return true;
}

function findSubCategory(categoryId) {
    $(".subSelect").hide();
    var data = {};
    data.categoryId = categoryId;
    $.ajax({
        url: golbalRootUrl + "catalog/subcategory",
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(data),
        success: function (data) {
            var subCategories = data.subCategories;
            if (subCategories.length > 0) {
                for (var i = 0; i < subCategories.length; i++) {
                    var subCategory = subCategories[i];
                    $("<option value='" + subCategory.categoryId + "'>" + subCategory.categoryName + "</option>").appendTo("#subCategory");
                }
                $(".subSelect").show();

            }
        }
    });
}
function searchUploadResult() {
    $("#s3uploadPage").html("");
    $("#s3uploadHistoryBody").html("");
    $("#s3uploadResultDiv").hide();
    var pageIndex = $("#pageIndex").val();
    var data = {};
    data.pageIndex = pageIndex;
    $.ajax({
        url: golbalRootUrl + "catalog/view/result",
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify(data),
        success: function (data) {
            var uploadHistories = data.uploadHistories;
            var total = data.total;
            var pageSize = data.pageSize;
            if (uploadHistories.length > 0) {
                var pageHtml = paging(uploadHistories, total, pageSize);
                $(pageHtml).appendTo("#s3uploadPage");
                for (var i = 0; i < uploadHistories.length; i++) {
                    var uploadHistory = uploadHistories[i];
                    var uploadDate = uploadHistory.uploadTime.toString().replace("T", " ").replace("Z", "");
                    var html = "<tr><td  style='width:163px'>" + uploadDate + "</td><td style='width:72px'>" + uploadHistory.historyId + "</td><td style='text-align: left;word-break:break-all;width:754px;'>Status:" + uploadHistory.status;
                    if (uploadHistory.errorMsg != undefined && uploadHistory.errorMsg != '') {
                        html += "<br>" + uploadHistory.errorMsg;
                    }
                    html += "</td><td>";
                    if (uploadHistory.status == "VALID_FAILURE") {
                        html += " <a onclick='downloadUploadProcessResult(this)' history-id='" + uploadHistory.historyId + "' href='javascript:void(0)'>View</a >";
                    }
                    html += "</td></tr>";
                    $(html).appendTo("#s3uploadHistoryBody");
                    $("#s3uploadHistoryBodyList tbody tr:even").addClass("pinkBg");
                }
                $("#s3uploadResultDiv").show();
            }
        }
    });
}

function downloadUploadProcessResult(obj) {
    var historyId = $(obj).attr("history-id");
    var url = golbalRootUrl + "catalog/download/result?historyId=" + historyId;
    window.open(url);
}

function prev() {
    var pageIndex = $("#pageIndex").val();
    $("#pageIndex").val(Number(pageIndex) - Number(1));
    searchUploadResult();
}

function next() {
    var pageIndex = $("#pageIndex").val();
    $("#pageIndex").val(Number(pageIndex) + Number(1));
    searchUploadResult();
}

function currentPage(currentNum) {
    $("#pageIndex").val(currentNum);
    searchUploadResult();
}

function paging(data, total, pageSize) {
    var html = "";
    if (data == "") {
        html = "<div class='errorResultMsg centerBox' style='width:400px;'>No search results found. Please refine your search filters and try again.</div>"
    } else {
        var pageIndex = $("#pageIndex").val();
        var pageNumber = total / pageSize;
        if (pageNumber > 1) {
            pageNumber = Math.ceil(pageNumber);
        } else {
            pageNumber = Math.floor(pageNumber);
        }
        html = "<div class='mt4 clearfix'><span class='font16 pr2'>" + total + "</span><span class='resultsText'>" + 'Results Returned' + "</span><div id='pager' class='pagerControl right'>";
        if (pageNumber > 1) {
            var prevstr = "";
            var nextstr = "";
            var pagestr = "";
            if (pageNumber == pageIndex) {
                prevstr = "<a href='javascript:void(0)' onclick='prev()'>&lt;Prev</a>";
                nextstr = "<span>Next&gt;</span>";
            } else if (pageIndex == 1) {
                prevstr = "<span>&lt;Prev</span>";
                nextstr = "<a href='javascript:void(0)' onclick='next()'>Next&gt;</a>";
            } else {
                prevstr = "<a href='javascript:void(0)' onclick='prev()'>&lt;Prev</a>";
                nextstr = "<a href='javascript:void(0)' onclick='next()'>Next&gt;</a>";
            }
            if (pageNumber > 8) {
                var pagetemp = "";
                for (var i = 1; i <= pageNumber; i++) {
                    if (i == pageIndex) {
                        pagetemp += "<span>" + i + "</span>";
                    } else if (i < pageIndex) {
                        var count = 2;
                        if (pageIndex == pageNumber) {
                            count = 3;
                        }
                        if (pageIndex - i < count) {
                            pagetemp += "<a href='javascript:void(0)' onclick='currentPage(" + i + ")'>" + i + "</a>";
                        }
                    } else {
                        var count = 2;
                        if (pageIndex == 1) {
                            count = 3;
                        }
                        if (i - pageIndex < count) {
                            pagetemp += "<a href='javascript:void(0)' onclick='currentPage(" + i + ")'>" + i + "</a>";
                        }
                    }
                }
                if (pageIndex <= 3) {
                    if (pageIndex == 3) {
                        pagetemp = "<a href='javascript:void(0)' onclick='currentPage(1)'>" + 1 + "</a>" + pagetemp;
                    }
                    pagestr += pagetemp + "......" + "<a href='javascript:void(0)' onclick='currentPage(" + (pageNumber - 1) + ")'>" + (pageNumber - 1) + "</a>" + "<a href='javascript:void(0)' onclick='currentPage(" + pageNumber + ")'>" + pageNumber + "</a>";
                } else if (pageIndex > pageNumber - 3) {
                    if (pageIndex == pageNumber - 2) {
                        pagetemp += "<a href='javascript:void(0)' onclick='currentPage(" + pageNumber + ")'>" + pageNumber + "</a>";
                    }
                    pagestr += "<a href='javascript:void(0)' onclick='currentPage(1)'>" + 1 + "</a>" + "<a href='javascript:void(0)' onclick='currentPage(2)'>" + 2 + "</a>" + "......" + pagetemp;
                } else {
                    pagestr += "<a href='javascript:void(0)' onclick='currentPage(1)'>" + 1 + "</a>" + "..." + pagetemp + "..." + "<a href='javascript:void(0)' onclick='currentPage(" + pageNumber + ")'>" + pageNumber + "</a>";
                }
            } else {
                for (var i = 1; i <= pageNumber; i++) {
                    if (i == pageIndex) {
                        pagestr += "<span>" + i + "</span>";
                    } else {
                        pagestr += "<a href='javascript:void(0)' onclick='currentPage(" + i + ")'>" + i + "</a>";
                    }
                }
            }
            html += prevstr + pagestr + nextstr;
        }
    }
    return html;
}